SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[spGenerarTriggerBajas] 
@tabla varchar(100),
@clave varchar(30)
AS
SET NOCOUNT ON
-- REALIZA UN TRIGGER UPDATE PARA MANEJAR ACTUALIZACIONES DE CAMPOS Baja Y FechaBaja

declare @SQLStm varchar(900)
select @SQLStm = 'CREATE TRIGGER BajasLogicas'+@tabla+' ON ['+@tabla+']'+char(10)
select @SQLStm = @SQLStm+'FOR UPDATE AS'+CHAR(10)
select @SQLStm = @SQLStm+'if update(baja) and (Select baja from inserted)=''S'' and (Select FechaBaja from inserted) is not null BEGIN'+char(10)
select @SQLStm = @SQLStm+char(9)+'UPDATE '+@tabla+' set FechaBaja = getdate() where '+@clave+'=(Select '+@clave+' from inserted)'+char(10)
select @SQLStm = @SQLStm+'END'+char(10)
select @SQLStm = @SQLStm+'else'+char(10)
select @SQLStm = @SQLStm+'if (update(baja) and (Select baja from inserted)=''N'')'
select @SQLStm = @SQLStm+char(9)+'UPDATE '+@tabla+' set FechaBaja= null where '+@clave+'=(Select '+@clave+' from inserted)'

print @SQLStm

exec(@SQLStm)
GO
